package cn.yangtianxia.org.service.impl;

import cn.yangtianxia.basic.service.impl.BaseServiceImpl;
import cn.yangtianxia.org.domain.Department;
import cn.yangtianxia.org.mapper.DepartmentMapper;
import cn.yangtianxia.org.service.IDepartmentService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 部门服务实现类
 */
@servicee
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Transactional
    @Override
    public void save(Department department) {
        departmentMapper.save(department);//返回自增Id
        this.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {
        //1.新增顶级部门  /自己id
        String dirPath = "";
        if(department.getParent() == null){
            dirPath = "/"+department.getId();
        }else{
            //2.新增非顶级部门
            // 2.1 获取上级部门的dirPath，拼接自己的id就可以了
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }
    /**
     * 无限极部门树
     * @return
     */
    @Override
    public List<Department> queryTree() {
        List<Department> departments = departmentMapper.loadAll();
        HashMap<Long, Department> allMap = new HashMap<>();
        for (Department department : departments){
            allMap.put(department.getId(),department);
        }
        List<Department> depts = new ArrayList<>();
        for(Department temp : departments){
            if(temp.getParent_id() == null){
                depts.add(temp);
            } else {
                Department parent = allMap.get(temp.getParent_id());
                if(parent != null){
                    parent.getChildren().add(temp);
                }
            }
        }
        return depts;
    }
}
